package com.only4play.authcenter.infrastructure.security.configurers.admin;

import com.only4play.authcenter.infrastructure.security.providers.admin.handler.CustomAuthenticationFailureHandler;
import com.only4play.authcenter.infrastructure.security.providers.admin.handler.CustomAuthenticationSuccessHandler;
import com.only4play.authcenter.infrastructure.security.providers.admin.password.PasswordLoginFilter;
import com.only4play.authcenter.infrastructure.security.providers.admin.password.PasswordProviders;
import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author hinzzz www.hinzzz.cn 157957329@qq.com
 * 2024-03-05
 */
public class PassLoginConfigurer extends AbstractHttpConfigurer<PassLoginConfigurer, HttpSecurity> {


    public static PassLoginConfigurer passLogin() {
        return new PassLoginConfigurer();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        ApplicationContext context = http.getSharedObject(ApplicationContext.class);
        CustomAuthenticationSuccessHandler successHandler = context.getBean(CustomAuthenticationSuccessHandler.class);
        CustomAuthenticationFailureHandler failureHandler = context.getBean(CustomAuthenticationFailureHandler.class);

        http.authenticationProvider(context.getBean(PasswordProviders.class));
        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        PasswordLoginFilter filter = new PasswordLoginFilter(builder.getObject());

        filter.setAuthenticationSuccessHandler(context.getBean(CustomAuthenticationSuccessHandler.class));
        filter.setAuthenticationFailureHandler(context.getBean(CustomAuthenticationFailureHandler.class));

        http.addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void init(HttpSecurity builder) throws Exception {
        super.init(builder);
    }
}
